/*
 * File Name:               UIClickOrPressButton.cs
 * 
 * Description:             普通类
 * Author:                  zhangke <kris@zhanng.org>

 * Create Date:             2017/07/31
 */

using UnityEngine;
using UnityEngine.EventSystems;

public class UIClickOrPressButton : UnityEngine.UI.Button
{
    public delegate void PressFunc(bool pressed);
    public delegate void ClickFunc();

    public PressFunc pressFunc;
    public ClickFunc clickFunc;

    public int clickMaxFrameCount = 10;

    bool isPointerDown;
    int pointerDownFrame;

    public void addListener(PressFunc callback)
    {
        pressFunc += callback;
    }

    public void addListener(ClickFunc callback)
    {
        clickFunc += callback;
    }

    public void removeListener(PressFunc callback)
    {
        pressFunc -= callback;
    }

    public void removeListener(ClickFunc callback)
    {
        clickFunc -= callback;
    }

    private void LateUpdate()
    {
        if (isPointerDown && pointerDownFrame <= clickMaxFrameCount)
        {
            pointerDownFrame += 1;

            if (pointerDownFrame > clickMaxFrameCount)
            {
                if (pressFunc != null)
                {
                    pressFunc.Invoke(true);
                }
            }
        }
    }

    public override void OnPointerDown(PointerEventData eventData)
    {
        base.OnPointerDown(eventData);
        isPointerDown = true;
        pointerDownFrame = 0;
    }

    public override void OnPointerUp(PointerEventData eventData)
    {
        base.OnPointerUp(eventData);
        excuteCallback();
    }

    public override void OnPointerExit(PointerEventData eventData)
    {
        base.OnPointerExit(eventData);
        excuteCallback();
    }

    void excuteCallback()
    {
        if (isPointerDown)
        {
            isPointerDown = false;
            if (pointerDownFrame <= clickMaxFrameCount)
            {
                if (clickFunc != null)
                {
                    clickFunc.Invoke();
                }
            }
            else
            {
                if (pressFunc != null)
                {
                    pressFunc.Invoke(false);
                }
            }
        }
    }
}